package com.shi.util;


import com.shi.common.ResultCodeEnum;
import com.shi.entity.po.Mail;
import com.shi.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class MailUtil {

    private static String sender; //邮件发送者

    private static JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    public void setSender(String sender) {
        MailUtil.sender = sender;
    }

    @Resource
    public void setJavaMailSender(JavaMailSender javaMailSender) {
        MailUtil.javaMailSender = javaMailSender;
    }

    /**
     * 发送文本邮件
     *
     * @param mail
     */
    public static void sendSimpleMail(Mail mail) {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(sender); //邮件发送者
            mailMessage.setTo(mail.getRecipient()); // 邮件发给的人
            mailMessage.setSubject(mail.getSubject());  // 邮件主题
            mailMessage.setText(mail.getContent());  // 邮件内容
            javaMailSender.send(mailMessage);
            log.info("邮件发送成功 收件人：{}", mail.getRecipient());
        } catch (Exception e) {
            log.error("邮件发送失败 {}", e.getMessage());
            throw new BusinessException(ResultCodeEnum.EMAIL_FORMAT_ERROR); //这是我自定义的一个异常码
        }
    }

}
